package com.yfq.springframework.beans.support;

import com.yfq.springframework.beans.config.BeanDefinition;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;

import java.lang.reflect.Constructor;

/**
 * @author: yfq
 * @date: 2023/2/1 8:48
 * @description:
 */
public class CglibSubClassInstantiationStrategy implements InstantiationStrategy {
    @Override
    public Object instantiate(String beanName, BeanDefinition beanDefinition, Constructor<?> constructor, Object... args) {
        Enhancer enhancer = new Enhancer();

        //设置代理类的类型
        enhancer.setSuperclass(beanDefinition.getBeanClass());

        //设置回调接口
        enhancer.setCallback(new NoOp() {
            @Override
            public int hashCode() {
                return super.hashCode();
            }

            @Override
            public boolean equals(Object obj) {
                return super.equals(obj);
            }
        });

        if (constructor == null) {
            return enhancer.create();
        }

        return enhancer.create(constructor.getParameterTypes(), args);
    }
}
